import { ref } from "vue"
//导入Http
import { Http } from "../http/users"
//导入信息提示
import { ElMessage } from "element-plus"
//导入store
import { useUserStore } from "../stores/users"
import router from "../router"
const store = useUserStore()
export const useUpdateUser = () => {
  //对话框显示
  const dialogVisible = ref(false)
  //用户信息
  const userForm = ref({
    username: store.user.username,
    password: store.user.password,
  })
  //表单ref
  //定义表单ref
  const userFormRef = ref()
  //表单规则
  const rules = ref({
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 2, max: 8, message: "长度在4~8个字符之间", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 4, max: 16, message: "长度在4~16个字符之间", trigger: "blur" },
    ],
  })
  const updateUser = () => {
    dialogVisible.value = true
  }
  //验证表单
  const submitForm = (formEl) => {
    if (!formEl) return
    formEl.validate(async (valid, fields) => {
      if (valid) {
        let data = await Http.updateUsers(store.user.id, {
          username: userForm.value.username,
          password: userForm.value.password,
          type: store.user.type,
        })
        if (data.code == 200) {
          ElMessage.success("修改信息成功,请重新登录")
          router.push("/")
        } else {
          ElMessage.error("修改信息失败")
        }
      } else {
        ElMessage.error("格式错误,请重新输入")
      }
    })
  }
  return { dialogVisible, updateUser, userForm, rules, submitForm, userFormRef }
}
